<?php

class UserController extends Zend_Controller_Action
{

    /**
     *
     * @return Form_Anonymous
     */
    private function getFmForm()
    {
        $form = new Form_Fm();
        $form->setAction($this->_helper->url->simple('anonymous'));

        return $form;
    }

    /**
     *
     * @return Form_Forgot 
     */
    private function getForgotForm()
    {
        $form = new Form_Forgot();
        $form->setAction($this->_helper->url->simple('forgot-password'));

        return $form;
    }

    /**
     *
     * @return Form_Registration
     */
    private function getRegistrationForm()
    {
        $form = new Form_Registration();
        $form->setAction($this->_helper->url->simple('save-registration'));

        return $form;
    }

    /**
     *
     * @return Form_Retrieve
     */
    private function getRetrieveForm()
    {
        $form = new Form_Retrieve();
        $form->setAction($this->_helper->url->simple('save-retrieve'));

        return $form;
    }

    /**
     *
     */
    public function indexAction()
    {
        
    }

    /**
     *
     */
    public function anonymousAction()
    {
        $form = new Form_Fm();
        if ($form->isValid($this->_request->getPost()))
        {
            $session = new Zend_Session_Namespace('fm');
            $session->fm = $form->getValue('fmName');

            $this->_helper->redirector->gotoRoute(array('name' => $form->getValue('fmName')), 'fm');
        }
        else
        {
            $this->_helper->PostForm->save();
            $this->_helper->redirector->gotoSimple('login', 'user', null, array('error_fm' => true));
        }
    }

    /**
     *
     */
    public function forgotAction()
    {

        $form = $this->getForgotForm();

        if ($this->_hasParam('error'))
        {
            $form->isValid($this->_helper->PostForm->retrieve());
        }

        $this->view->form = $form;
    }

    /**
     *
     */
    public function forgotPasswordAction()
    {

        if (!$this->getRequest()->isPost())
        {
            $this->_helper->redirector->gotoSimple('index');
        }

        $form = $this->getForgotForm();

        if ($form->isValid($this->_request->getPost()))
        {
            $email = $form->getValue('email');

            $db = Zend_Db_Table::getDefaultAdapter();
            $user_id = $db->fetchOne($db->select()->from('user', 'id')->where('email = ?', $email));

            $random = sha1(rand() . $email);


            // smazeme predchozi requesty
            $db->delete('forgot', 'user_id = ' . $user_id);
            // smazeme zaznamy starsi nez 1 hodinu
            $db->delete('forgot', "expire < ADDDATE(NOW(), INTERVAL -1 HOUR)");

            $db->insert('forgot',
                    array(
                        'expire' => new Zend_Db_Expr('ADDDATE(NOW(), INTERVAL +1 HOUR)'),
                        'hash' => $random,
                        'ip' => $this->_request->getClientIP(),
                        'user_id' => $user_id
            ));

            $url = $this->_request->getScheme() . '://' .
                    $this->_request->getHttpHost() .
                    $this->getFrontController()->getBaseUrl() .
                    "/user/retrieve-password?reset=" . $random;

            //nyni je v tabulce informace a ted odesleme maila uzivateli
            $body = "Vážený uživateli, pokud jste si vyžádal změnu hesla prosím,
                klikněte na následující odkaz:
                $url
                Nové heslo si můžete změnit hodinu po vašem požadavku. Mějte prosím na paměti, že
                IP adresa, ze které přistupujete ke změně hesla musí odpovídat IP adrese ze které vzešel
                požadavek.";

            //Tuhle adresu je treba poslat mailem

            $mail = new Zend_Mail('UTF-8');
            $mail->setSubject('Ultimate Playlist - Žádost o nové heslo');
            $mail->setBodyText($body);
            $mail->addTo($form->getValue('email'));

            //$mail->send();

            $this->_helper->redirector->gotoSimple('forgot-email-sent');
        }
        else
        {
            //pokud ne:
            $this->_helper->PostForm->save();
            $this->session->msg = 'error';

            $this->_helper->redirector->gotoSimple('forgot', null, null, array('error' => 1));
        }
    }

    /**
     * 
     */
    public function forgotEmailSentAction()
    {
        
    }

    /**
     *
     * @return Facebook 
     */
    private function getFacebook()
    {
        $front = Zend_Controller_Front::getInstance();

        $bootstrap = $front->getParam('bootstrap');

        $application = $bootstrap->getApplication();

        // nacteme si konfiguraci a zjistime klic k API

        $config = new Zend_Config($application->getOptions());
        $api_key = $config->facebook->app_key;
        $secret = $config->facebook->app_secret;

        return new Facebook(array(
            'appId' => $api_key,
            'secret' => $secret,
            'cookie' => false,
        ));
    }

    /**
     *
     */
    public function loginAction()
    {

        if (Zend_Auth::getInstance()->hasIdentity())
        {
            $this->_helper->redirector->gotoRoute(array('name' => User::getActiveUser()->getLastFmName()), 'fm');
        }


        $front = Zend_Controller_Front::getInstance();

        $bootstrap = $front->getParam('bootstrap');

        $application = $bootstrap->getApplication();

        $config = new Zend_Config($application->getOptions());
        $api_key = $config->lastfm->app_key;


        $this->view->api_key = $api_key;
        $this->view->cb = "http://".$this->getRequest()->getServer("HTTP_HOST");


        // Create our Application instance (replace this with your appId and secret).

        $facebook = $this->getFacebook();
        $facebook_login_url = $facebook->getLoginUrl(array('req_perms' => 'email'));


        $login_form = new Form_Login();
        $fm_form = $this->getFmForm();

        if ($this->_getParam('error_fm'))
        {
            $this->_response->setHttpResponseCode(401);
            $fm_form->isValid($this->_helper->PostForm->retrieve());
        }

        if ($this->_getParam('login-failed'))
        {
            $this->_response->setHttpResponseCode(401);
            $flash = $this->_helper->FlashMessenger;
            $this->view->errors = $flash->setNamespace('login')->getMessages();
        }

        $this->view->headTitle("Logovací stránka");
        $this->view->fm_form = $fm_form;
        $this->view->login_form = $login_form;
        $this->view->facebook_login_url = $facebook_login_url;
    }

    /**
     *
     */
    public function logoutAction()
    {
        $facebook_id = null;

        if (Zend_Auth::getInstance()->hasIdentity())
        {
            $user = User::getActiveUser();

            $facebook_id = $user->facebook_id;
        }


        $auth = Zend_Auth::getInstance();

        $auth->clearIdentity();

        $session = new Zend_Session_Namespace('fm');
        $session->unsetAll();

        if ($facebook_id)
        {
            $cookie = $this->getFacebook()->setSession();

            header('Location:' . $this->getFacebook()->getLogoutUrl());
            exit;
        }

        $this->_helper->redirector->gotoSimple('login', 'user');
    }

    /**
     * 
     */
    public function registerAction()
    {
        $facebook = $this->getFacebook();
        $facebook_login_url = $facebook->getLoginUrl(array('req_perms' => 'email'));

        $form = $this->getRegistrationForm();

        if ($this->_hasParam('error'))
        {
            $form->isValid($this->_helper->PostForm->retrieve());
        }


        $this->view->form = $form;
        $this->view->facebook_login_url = $facebook_login_url;
    }

    /**
     *
     */
    public function retrievePasswordAction()
    {
        $db = Zend_Db_Table::getDefaultAdapter();
        // smazeme zaznamy starsi nez 1 hodinu
        $db->delete('forgot', "expire < ADDDATE(NOW(), INTERVAL -0 HOUR)");
        $form = $this->getRetrieveForm();
        if ($this->_request->isPost())
        {
            $form->isValid($this->_request->getPost());
        }
        else if ($this->_hasParam('error'))
        {
            $form->isValid($this->_helper->PostForm->retrieve());
        }

        if (!$form->getElement('hash')->getValue())
        {
            $hash = $this->_getParam('reset');

            $select = $db->select()->from('forgot', 'hash')
                            ->where('hash = ?', $hash);
            $hash = $db->fetchOne($select);
            if ($hash)
            { //pokud je hash v tabulce pak OK
                $form->getElement('hash')->setValue($hash);
            }
            else
            {
                //pokud ne presmeruju na forgot
                $session = new Zend_Session_Namespace('forgot');
                $session->forgot = 'Hash již není validní nebo neexistuje!';
                $this->_helper->redirector->goToSimple('forgot');
            }
        }

        $this->view->form = $form;
    }

    /**
     *
     */
    public function saveRetrieveAction()
    {
        if (!$this->getRequest()->isPost())
        {
            $this->_helper->redirector->gotoSimple('index');
        }
        $form = $this->getRetrieveForm();
        if ($form->isValid($this->_request->getPost()))
        {
            //je validni - updatneme heslo!
            $password = sha1($form->getValue('password1'));
            $hash = $form->getValue('hash');
            $db = Zend_Db_Table::getDefaultAdapter();

            $table = 'forgot';
            $select = $db->select()
                            ->from($table, 'user_id')
                            ->where('hash', $hash);

            $user_id = $db->fetchOne($select);

            $where = $db->quoteInto("id = ?", $user_id);

            $update = $db->update('user', array('password' => $password), $where);

            //je updatnuto ... smaznem tedy tu hashku
            $table = 'forgot';

            $delete = $db->delete($table, $db->quoteInto("hash = ?", $hash));
        }
        else
        {
            //neni validni
            $this->_helper->PostForm->save();
            $this->session->msg = 'Ve formuláři jsou chybně vyplněné položky';

            $this->_helper->redirector->gotoSimple('retrieve-password', null, null, array('error' => 1));
        }
    }

    /**
     *
     */
    public function saveRegistrationAction()
    {
        if (!$this->getRequest()->isPost())
        {
            $this->_helper->redirector->gotoSimple('index');
        }

        $form = $this->getRegistrationForm();

        if ($form->isValid($this->_request->getPost()))
        {

            $db = Zend_Db_Table::getDefaultAdapter();

            $allowed_columns = array('first_name', 'last_name', 'email', 'last_fm_username');
            $set = array();

            foreach ($allowed_columns as $key)
            {
                $set[$key] = $form->getValue($key);
            }

            $set['password'] = sha1($form->getValue('password1'));

            $table = 'user';
            $db->insert($table, $set);

            $mail = new Zend_Mail('UTF-8');
            $mail->setSubject('Registrace na Ultimate Playlist');
            $mail->setBodyText('bla bla');
            $mail->addTo($form->getValue('email'));

            //$mail->send();

            $_POST['email'] = $form->getValue('email');
            $_POST['password'] = $form->getValue('password1');
            $_POST['login'] = 1;

            $auth = $this->getFrontController()->getPlugin('Application_Plugin_DbAuth');
            $auth->preDispatch($this->_request);

            $this->_helper->redirector->gotoSimple('login');
        }
        else
        {
            $this->_helper->PostForm->save();
            $this->session->msg = 'Ve formuláři jsou chybně vyplněné položky';

            $this->_helper->redirector->gotoSimple('register', null, null, array('error' => 1));
        }
    }

    public function accountAction()
    {
        $form = new Form_Account();

        if (!Zend_Auth::getInstance()->hasIdentity())
        {
            $this->_helper->redirector->gotoSimple('login');
        }

        $user = User::getActiveUser();


        if ($this->_request->getParam('remove-cache'))
        {
            $cache = $this->_helper->cache->getCache('lastfm');

            $cache->clean(
                    Zend_Cache::CLEANING_MODE_MATCHING_TAG,
                    array(strtolower(LastFM_User::getActiveUser()->getName()))
            );

            $this->view->cache_removed = true;
        }

        if ($this->_request->isPost())
        {
            if ($form->isValid($this->_request->getPost()))
            {
                $set = $form->getValues();


                foreach ($set as $key => $val)
                {
                    $user->$key = $val;
                }

                $user->save();

                $this->view->valid = true;
            }
            else
            {
                $this->view->valid = false;
            }

        }
        else
        {
            $form->setDefaults($user->toArray());
        }

        $this->view->form = $form;
    }

}

